<template>
	<view  :style="{ 'padding-top': top + 'px' }">
				 <yk-authpup ref="authPupYk" type="top" @changeAuth="authSuccess" :permissionID="permissionID"></yk-authpup>
		<view class="area-header">
			<view class="header-select flex-row justify-between " style="padding: 20rpx 24rpx 10rpx"  >
				<view class="select-region flex-row justify-between"  @click="oncity" v-if="currentdistancec.city">

						<view class="flex-row items-center group" >
						  <image v-if="type==1"
						    class="shrink-0 image_4"
						    src="https://qiniu.ccchongya.com/chongya/images/16947555487802052701.png"
						  />
						  <image v-else
						    class="shrink-0 image_4"
						    src="https://qiniu.ccchongya.com/chongya/images/16967453055641285259.png"
						  />
						  <text class="flex-row font_2 text_2 myicon myicon-arrow-down-after  " style="padding-right:10px;" >{{currentdistancec?currentdistancec.city:'全国' || city}}
						  </text>
						</view>
						<!-- 	<text   class="flex f-a-c f-j-c myicon myicon-arrow-down f10-size t-color-b"></text> -->

				</view>
				<view class="select-input">
					<!-- <text class="input_holder" style="margin: 0 10px;">|</text> -->
					<input v-model="keyword" @input="input" placeholder-class="input_holder" placeholder="请输入地点" />
					<uni-icons type="search" size="22" style="margin-right: 15rpx;" color="#D8D8D8"></uni-icons>
				</view>
				<view class="flex justify-between items-center " style="padding:0 10px" @tap="clear">
					取消
				</view>

			</view>
		</view>

			<view class="" >

				<view class="current_position">
					<view>

						<text class="position_text">当前位置</text>
					</view>
				</view>
				<view class="position_ul">
					<block v-if="currentAddressinfo">
						<view>
							<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-weizhi f14-size t-color-y1"></text>
						</view>
						<view class="address">
							<text class="current-address" @click="checkcurrent(currentAddressinfo)">{{currentAddressinfo.address}}</text>
						</view>
					</block>

					<block v-else>
						<view class="address">
							<text class="current-address" >暂时没有获取到您的位置</text>
						</view>
					</block>
					<view class="dingweis_div" @click="getMyLocation">
						<text>{{po_tips}}</text>
					</view>

				</view>
			</view>



		<view class="area-site">
			<view>
				<view class="current_position">
					<view>
						<text class="position_text">搜索结果</text>
					</view>
				</view>
				<view @click="checkdizhi(item,true)" v-for="(item,index) in searchResults" :key="item.id" class="position_ul 1">
					<view>
			<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-weizhi f14-size t-color-y1"></text>
					</view>
					<view class="address">
						<text class="address-name">{{item.name}}</text>
						<text class="current-address">{{item.district}}{{item.address}}</text>
					</view>
					<view class="distance_text">
						<text>{{item.distance}}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="history-content" v-if="searchResults.length === 0">
			<view class="current_position">
				<view>
					<image src="@/static/images/task/history.png" class="position_img"></image>
					<text class="position_text">历史记录</text>
				</view>
				<view @click="clearHistory" class="clear_history">清空</view>
			</view>

			<view v-if="historyList.length===0" class="history_none" style="padding: 20px;">
				暂无历史记录
			</view>
			<view>
				<view  @click="checkdizhi(item,false)"  v-for="(item,index) in historyList" :key="item.id" class="position_ul 2">
					<view>


						<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-address f14-size t-color-y1"></text>
				<!-- 		<image src="@/static/images/task/icon-positioning.png"
							style="width: 16px;height: 16px;margin-right: 7.5px;"></image> -->
					</view>
					<view class="address">
						<text class="address-name">{{item.name}}</text>
						<text class="current-address">{{item.district}}{{item.address}}</text>
					</view>
					<view class="distance_text">
						<text>{{item.distance}}</text>
					</view>
				</view>
			</view>
		</view>

		<popup-layer ref="popupRef" :direction="'right'">
			<view style="width:750upx;height: 100%;">
				<citySelect @back_city="back_city"  :currentAddressinfo="currentAddressinfo"></citySelect>
			</view>
		</popup-layer>



	</view>
</template>

<script>


	import citySelect from '@/components/linzq-citySelect/linzq-citySelect.vue';
	import popupLayer from '@/components/popup-layer/popup-layer.vue';



	export default {

		components: {
			citySelect,
			popupLayer
		},
		data() {
			return {
				_hasPrmissionLocation:this.hasPrmissionLocation,
				permissionID:'ACCESS_FINE_LOCATION',
				top: uni.getStorageSync('bartop') ? uni.getStorageSync('bartop') : 0,
				type:1,
				region:"请选择...",
				position:"",
				po_tips: '重新定位',
				timer: null,
				myAmapFun: null, // 高德获取地址
				keyword: '', // 用户输入的关键词
				searchResults: [], // 搜索提示结果
				historyList: [], // 历史记录
				gaodekey: 'key', // 高德的key
				currentname: "", // 地址标题
				currentaddress: "", // 已经获取到当前的位置
				city: '北京',
				addresstype: '',
				currentlat: '', // 当前位置纬度
				currentlng: '', // 当前位置经度
				currentdistancec: '', // 当前位置距离
currentAddressinfo:{
				    latitude:"",
					longitude:"",
					address:"",
					region:"",
					city:"",
					citycode:"",
					district:"",
					province:"",
				},
				chooseAddressinfo:{
					latitude:"",
					longitude:"",
					address:"",
					region:"",
					city:"",
					citycode:"",
					district:"",
					province:"",
				},
				// currentAddressinfo:{
				//     latitude:"",
				// 	longitude:"",
				// 	address:"",
				// 	region:"",
				// 	city:"",
				// 	citycode:"",
				// 	district:"",
				// 	province:"",
				// },

			}
		},
		props: {
			hasPrmissionLocation: {
				type: Boolean,
				default: false
			},
			// currentAddressinfo: {
			// 	type: Object,
			// 	default:() => {
			// 		return {
			// 	    latitude:"",
			// 		longitude:"",
			// 		address:"",
			// 		region:"",
			// 		city:"",
			// 		citycode:"",
			// 		district:"",
			// 		province:"",
			// 	}
			// 	}
			// },
			// chooseAddressinfo: {
			// 	type: Object,
			// 	default:() => {
			// 		return {
			// 	    latitude:"",
			// 		longitude:"",
			// 		address:"",
			// 		region:"",
			// 		city:"",
			// 		citycode:"",
			// 		district:"",
			// 		province:"",
			// 	}
			// 	}
			// }
			// selectProductItem: {
			// 	type: Object | Array,
			// 	default() {
			// 		return [] || {};
			// 	}
			// },


		},
		watch: {
			  city(newData){
			     this.searchTips()
			  },
			  // currentAddressinfo(newData){
			  //     console.log("currentAddressinfo change 111",n)
			  // },
			  // currentAddressinfo(val) {
				// 	this.currentAddressinfo()
				// }
			 hasPrmissionLocation: {
				handler(n, o) {


								console.log("hasPrmissionLocation handler",)
								this._hasPrmissionLocation = n
								// 获取当前位置
								if(n){
											this.getMyLocation()
								}
				},
				immediate:true,
				//该回调会在任何被侦听的对象的 property 改变时被调用，不论其被嵌套多深
				deep: true
			  },
			  currentAddressinfo: {
			  	handler(n, o) {

					this.initdata()
			  	},
			  	immediate:true,
			  	//该回调会在任何被侦听的对象的 property 改变时被调用，不论其被嵌套多深
			  	deep: true
			  }
		},
		mounted(evenlett) {
			let _this = this;

			_this.historyList = JSON.parse(uni.getStorageSync('historylist') || '[]')
		},


		onShow() {
			that.chooseAddressinfo  = uni.getStorageSync('chooseAddressinfo') || {};
			that.currentAddressinfo  = uni.getStorageSync('currentAddressinfo') || {};

				let _this = this;
				uni.$on('region',function(data){
					console.log('监听到事件来自 region ，携带参数 msg 为：'  + data);
					_this.city = data;
				})

				// _this.currentaddress =  	uni.getStorageSync('currentaddress');

				// this.$nextTick(function () {
				//      this.$bus.$emit("yulan", row);
				//  })







		},



		methods: {
			clear(){
				this.$emit('back_address_clear', 'no');
			},
			oncity() {
				var _this = this

				if(_this.autoLocation){
					uni.navigateTo({
						url: `/pages/a`
					});
				}else{
					this.$refs.popupRef.show();

				}

			},
			back_city(e) {
				// console.log("e",e)
				if (e !== 'no') {
					this.city = e.cityName
					this.$refs.popupRef.close();
				} else {
					this.$refs.popupRef.close();
				}
			},
			 initdata(){
				 this.currentaddress = this.currentAddressinfo.address
				 // this.city = this.currentAddressinfo.city

				  this.city = this.chooseAddressinfo.city


			 },
			 // //这个是自己的方法名
			 openAuthYk(permissionID){
			 	setTimeout(()=>{
			 	    this.permissionID = permissionID;
			 		this.$refs.authPupYk.open();
			 	},1000)
			 },
			 //权限获取后的回调函数
			 authSuccess(permissionID){
			 	if(	permissionID =="ACCESS_FINE_LOCATION"){
			 							this._hasPrmissionLocation = true;
			 							this.getMyLocation()
			 	}
			 },

			// 获取当前位置
			getMyLocation() {
				console.log("11111111111")
				let _this = this;


				if(!_this._hasPrmissionLocation){
					// that.addresstext = "请选择你的地址"
					_this.openAuthYk("ACCESS_FINE_LOCATION")
					return
			   }


				_this.po_tips = '定位中...'
				console.log(_this.po_tips)
				_this.mapfun.getlocation().then(res => {
					// console.log("res",res)
					_this.mapfun.getCityinfo().then(res => {
								_this.region =  res.addressComponent.province+res.addressComponent.city
								_this.city = (res.addressComponent.city.length>0)? res.addressComponent.city: res.addressComponent.province;
								_this.currentaddress = res.formatted_address
										// console.log("res2",res)
										// 	console.log("res2",res)
								let longitude =  uni.getStorageSync('longitude');
								let latitude = uni.getStorageSync('latitude');
								_this.currentlat = longitude // 当前位置纬度
								_this.currentlng = latitude // 当前位置经度
								_this.currentdistancec = _this.mapfun.getDistance(_this.currentlat, _this.currentlng, _this.currentlat, _this.currentlng ) // 当前位置经度
								_this.po_tips = '重新定位'


								// console.log("_this.currentdistancec",_this.currentdistancec)

								let currentAddressinfo = {};
								_this.currentAddressinfo.latitude = latitude
								_this.currentAddressinfo.longitude = longitude
								_this.currentAddressinfo.address = _this.currentaddress
								_this.currentAddressinfo.region = _this.regiontext

								_this.currentAddressinfo.city = _this.city
								_this.currentAddressinfo.citycode = res.addressComponent.citycode;
								_this.currentAddressinfo.district = res.addressComponent.district;
								_this.currentAddressinfo.province = res.addressComponent.province;
								_this.currentAddressinfo.country =  res.addressComponent.country;

								uni.setStorageSync('currentAddressinfo',_this.currentAddressinfo);
								// console.log("_this.currentAddressinfo",_this.currentAddressinfo)

								uni.hideLoading();
					}).catch(err => {
						// console.log("暂无当前位置信息111111",err)
								_this.currentname = "暂无当前位置信息"
								_this.currentAddressinfo.address = _this.currentname
								_this.po_tips = '重新定位'
					})
				}).catch(err => {
						_this.currentname = "暂无当前位置信息"
						_this.currentAddressinfo.address = _this.currentname
							// console.log("暂无当前位置信息2")
							// 		console.log(_this.currentAddressinfo.address)

				})
			console.log("console.log(_this.currentAddressinfo.address)”",_this.currentAddressinfo.address)

			this.$emit('handleCurrentAddressinfo', 	_this.currentAddressinfo);
			},
			// 搜索地址
			searchTips() {
				let _this = this;
				if (_this.keyword === '') {
					_this.searchResults = []
					return
				}

				// 发起搜索提示请求

				// _this.mapfun.getInputtips().then(res => {
				// 					console.log("getInputtips11111")
				// }).catch(err => {
				// 	console.log("getInputtips2222")



				// })


				_this.mapfun.getInputtips({
					keywords: _this.keyword,
					city: _this.city, //必须填写搜索的城市
					success(data) {
						if (data && data.tips) {
							const arr = JSON.parse(JSON.stringify(data.tips))
							for (let i of arr) {
								const str = i.location
								if (str.length !== 0) {
									const dis = str.split(',')
									const distance = _this.mapfun.getDistance(_this.currentlat,_this.currentlng, dis[1], dis[0])
									i.distance = distance
								}
							}
							arr.shift()
							_this.searchResults = arr;
							// console.log("_this.searchResults.",_this.searchResults)
						}
					},
				});

				// this.myAmapFun.getInputtips({
				// 	keywords: this.keyword,
				// 	city: this.city, //必须填写搜索的城市
				// 	success(data) {
				// 		if (data && data.tips) {
				// 			const arr = JSON.parse(JSON.stringify(data.tips))
				// 			for (let i of arr) {
				// 				const str = i.location
				// 				if (str.length !== 0) {
				// 					const dis = str.split(',')
				// 					const distance = _this.getDistances(_this.currentlat,_this.currentlng, dis[1], dis[0])
				// 					i.distance = distance
				// 				}
				// 			}
				// 			_this.searchResults = arr;
				// 		}
				// 	},
				// });
			},

			//搜索函数防抖
			input(e) {
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.searchTips()
				}, 500)
			},
			// 选择地址
			checkdizhi(item,add) {
				let _this = this
				if(add){
					_this.saveSearchHistory(item) // 保存历史记录
				}

				let e = item


				let adinfo  = _this.mapfun.matchAddresInfo( e.district);

	            // uni.setStorageSync('chooseAddressinfo',e);
				_this.longitude =  e.location.split(',')[0] // 当前位置纬度
				_this.latitude =  e.location.split(',')[1] // 当前位置经度
				if (e !== 'no') {
					_this.addresstext = e.name
				} else {
				}



				let newitem={}

				newitem.address = e.name
				newitem.province = adinfo[0];
				newitem.city =adinfo[1];
				newitem.district = adinfo[2];
				newitem.latitude = e.location.split(',')[0] // 当前位置纬度
				newitem.longitude = e.location.split(',')[1] // 当前位置经度
				newitem.region ="";

				newitem.distance = e.distance


				_this.checkGo(newitem)


			},
			// 点击当前位置选择地址
			checkcurrent(item) {
				let _this = this
				_this.checkGo(item)


				// const address = item.district + item.address + item.name
				// 				console.log("item",item)
				// 				uni.navigateBack({
				// 					delta: 1 //返回上一页
				// 				})

				// if (this.addresstype == "startAddress") {
				// 	uni.$emit('startAddress', item)
				// 	uni.navigateBack({
				// 		delta: 1 //返回上一页
				// 	})
				// }
				// if (this.addresstype == "endAddress") {
				// 	uni.$emit('endAddress', item)
				// 	uni.navigateBack({
				// 		delta: 1 //返回上一页
				// 	})
				// }
			},
			checkGo(item){
						const address = item.district + item.address + item.name
						this.back_address(item);
						// uni.navigateBack({
						// 	delta: 1 //返回上一页
						// })
			},
		back_address(item) {
			if (item) {
				this.$emit('back_address', item);
				// //unshift 把数据插入到首位，与push相反
				// this.Visit.unshift(item)
				// this.searchValue = "";
				// this.disdingwei = true
				// var arr = this.Visit
				// //数组去重
				// function distinct(arr) {
				// 	let newArr = []
				// 	for (let i = 0; i < arr.length; i++) {
				// 		if (newArr.indexOf(arr[i]) < 0) {
				// 			newArr.push(arr[i])
				// 		}
				// 	}
				// 	return newArr
				// }
				// this.Visit = distinct(arr)
				// console.log(this.Visit, "---最近访问")
				// uni.setStorage({
				// 	key: 'Visit_key',
				// 	data: this.Visit
				// });
			} else {
				this.$emit('back_address_clear', 'no');
			}

		},
			// 清空搜索历史记录
			clearHistory() {
				uni.showModal({
					title: '提示',
					content: '是否清空搜索历史',
					success: (res) => {
						this.historyList = []
						uni.setStorageSync('historylist', '[]')
					}
				})
			},
			// 保存搜索历史并持久化
			saveSearchHistory(item) {
				this.historyList.unshift(item) // 把新数据添加到数组最后
				const string = this.historyList.map((index) => JSON.stringify(index)) // 把数组每一项转为字符串
				const removeDupList = Array.from(new Set(string)) //去重后再转为数组
				const result = removeDupList.map((item) => JSON.parse(item)) // 把数组每一项转为对象
				uni.setStorageSync('historylist', JSON.stringify(result))
			},
			// 改变城市
			changeCity() {
				uni.navigateTo({
					url: `/pages/task/area/selectregion`
				});
			},
		}
	}
</script>

<style lang="scss">

	.myicon-arrow-down-after:after {
		margin-left:4px;
		display: flex;
		flex-direction:row;
		align-items: center;
		font-size: 5px;
		content: "\e637";
	}


.height {
		height: var(--status-bar-height);
	}

	.group {
	  padding-left: 0rpx;
	}
	.image_4 {
	  width: 38rpx;
	  height: 38rpx;
	}
	.font_2 {
	  /* font-size: 24rpx; */
	  font-family: HarmonyOSSansSC;
	  line-height: 22rpx;
	  color: #666e7a;
	}
	.text_2 {
	  margin-left: 8rpx;
	  /* color: #ffffff; */
	}




	.dingwei {
		width: 100%;
		padding-top: 25upx;
		box-sizing: border-box;
		margin-bottom: 26upx;
	}

	.dingwei_Tips {
		margin-left: 24upx;
		margin-bottom: 24upx;
		font-size: 24upx;
		color: #A5A5A5;
	}

	.dingwei_city {
		width: 100%;
		height: 60upx;
		padding-left: 55upx;
		padding-right: 70upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}

	.dingwei_city_one {
		width: 185upx;
		height: 60upx;
		background-color: #ffffff;
		border-radius: 10upx;
		font-size: 32upx;
		color: #333333;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dingweis_div {
		display: flex;
		align-content: flex-end;
		align-items: center;
		font-size: 24upx;
		color: #FD5745;
	}




	#container {
		width: 300px;
		height: 200px;
	}

	// 搜索栏
	.area-header {
		background-color: #fff;
		// padding: 22px  0 0 0;
		// margin-top:10px;

		.header-select {

			padding: 20rpx 5rpx;
			display: flex;
			flex-direction: row;
		    // align-items:stretch;
		  flex-grow: 1;
			// 左侧的城市名
			.select-region {

				flex:1;

				.region_text {
					font-size: 16px;
				}
			}


			// 右侧输入地址
			.select-input {
				padding:10rpx 20rpx;
				border-radius: 10rpx;
				background-color: #F3F3F3;
				width:100%;
				display: flex;
				flex-direction: row;
				flex:5;
				flex-grow: 2;
				justify-content: space-between;
				.input_holder {
					color: #D8D8D8;
					font-size: 16px;
				}
			}
		}
	}

	// 地址栏
	.position_ul {
		background-color: #fff;
		padding: 10px 20px;
		display: flex;
		align-items: center;
		border-bottom: 1px solid #F3F3F3;

		.address {
			flex: 5;
			margin:0 40rpx 0 10px;

			.address-name {
				font-size: 16px;
			}

			.current-address {
				margin-top: 2px;
				font-size: 12px;
				color: #C0C4CC;
				display: flex;
				flex-direction: column;
			}
		}

		.distance_text {
			flex: 1;
			margin-left: 10px;
			font-size: 12px;
			color: #C0C4CC;
		}

		// 位置距离
		.site-distance {}
	}



 // 提示信息（当前位置/历史记录）
 .current_position {
 	padding: 12px 22px;
 	display: flex;
 	justify-content: space-between;
 	align-items: center;

 	.position_img {
 		width: 12px;
 		height: 12px;
 		margin-right: 7.5px;
 		line-height: 21px;
 		vertical-align: middle;
 	}

 	.position_text {
 		font-size: 12px;
 		color: #303133;
 		line-height: 21px;
 	}

 	// 清空历史
 	.clear_history {
 		font-size: 12px;
 		color: #2979FF;
 	}
 }


	// 选择地点历史记录
	.history-content {

		// 无历史记录提示信息
		.history_none {
			background-color: #fff;
			padding: 20px 10px;
			color: #C0C4CC;
		}

		// 提示信息（当前位置/历史记录）
		.current_position {
			padding: 12px 22px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.position_img {
				width: 12px;
				height: 12px;
				margin-right: 7.5px;
				line-height: 21px;
				vertical-align: middle;
			}

			.position_text {
				font-size: 12px;
				color: #303133;
				line-height: 21px;
			}

			// 清空历史
			.clear_history {
				font-size: 12px;
				color: #2979FF;
			}
		}
	}
</style>
